import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

//事件产生时，传递的数据,这里主要指回调函数.
interface IEventData
{
    func:Function;
    target:any;
}

interface IEvent
{
    [eventName:string]:IEventData[];
}

@ccclass('CustomEventListener')
export class CustomEventListener extends Component {
    public static handle:IEvent = {};

    //当某个事件发生时，注册对此事件的响应.
    public static on(eventName:string,cb:Function,target?:any){
        if(!this.handle[eventName])
        {
            this.handle[eventName] = [];
        }
        const data:IEventData = {func:cb,target};
        this.handle[eventName].push(data);
    }

    //取消对事件的注册，通常是注册事件的类的对象回收的时候(或隐藏、未激活的时候).
    public static off(eventName:string,cb:Function,target?:any){
        const list = this.handle[eventName];
        if(!list || list.length<=0){
            return;
        }
        for (let i = 0; i < list.length; i++) {
            const event = list[i];
            if(event.func === cb && (!target || target===event.target)){
                list.splice(i,1);
                break;
            }
        }
    }

    //发布事件，即通知所有注册了该事件的类的对象，该事件发生了.
    public static dispatchEvent(eventName:string, ...args:any){
        const list = this.handle[eventName];
        if(!list || list.length<=0){
            return;
        }
        for (let i = 0; i < list.length; i++) {
            const event = list[i];
            event.func.apply(event.target,args);
        }
    }
}
